const shopModel = require('../models/shopModel')
const typeModel = require('../models/typeModel')
const {Op} = require('sequelize')

module.exports ={
    getAllTypes:async() =>{
        let whereObj = {}
        try{
            let types = await typeModel.findAll({
                  where:whereObj,
              })
            return types
          }catch(error){
            console.log("find all types error:",error);
            return false
          }
    },
    getShopbyId:async(id) =>{
      try{
          let result = await shopModel.findOne({
              where:{
                  id
              },
              include:[{
                  model:typeModel
              }],
          });                  
            return result
      }catch(error){
          console.error('find shop by id error:'+error);
          return false
      }
  },
    getAllShopsBySearch:async(id,shopname, shoptype) =>{
        let whereObj = {}

        id && Object.assign(whereObj,{id:id})

        shopname && Object.assign(whereObj,{
            shopname:{
                [Op.like]:`%${shopname}%`
            }          
        })

        shoptype && Object.assign(whereObj,{type:shoptype})
        try{
          let count = await shopModel.count({where:whereObj});
          console.log(count);
          let shops;
          if(count !==0){
            shops = await shopModel.findAll({
                include:[{
                    model:typeModel
                }],
                where:whereObj,
            })
          }
          console.log(shops)
          return {shops:shops} || null
        }catch(error){
          console.log("find all shops error:",error);
          return false
        }
    },
    deleteShopbyId:async(id) =>{
      try{
          let result = await shopModel.destroy({
              where:{
                  id
              }
          })
          return result
      }catch(error){
          console.error('delete shop by id error:'+error);
          return error
      }
  },
  addShop:async(id,shopName,type, path, price) =>{
    try{
        let result = await shopModel.create({
          id,
          shopName,
          type,
          path, 
          price
        })
      console.log(result)
      return result
    }catch(error){
        console.error('add shop error:'+error);
        return error
    }
},
updateShopbyUserId:async(id,shopName,type, price) => {
  try{
    let result = await shopModel.findOne({
        where:{
            id
        }
    }).then((emp) =>{
        emp.update({
          shopName,
          type,
          price
        })
        return emp
    })
    return result
}catch(error){
    console.error('update shop by id error:'+error);
    return error
}

}
}